package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.BaseBasketballPlayer;
import com.ruoyi.system.domain.BaseBasketballTeam;
import com.ruoyi.system.domain.BaseTeanGroupingPlayTeam;
import com.ruoyi.system.service.IBaseBasketballTeamService;
import com.ruoyi.system.service.IBaseTeanGroupingPlayTeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.BaseTeamGroupingMapper;
import com.ruoyi.system.domain.BaseTeamGrouping;
import com.ruoyi.system.service.IBaseTeamGroupingService;
import org.springframework.transaction.annotation.Transactional;

import static java.util.stream.Collectors.counting;

/**
 * 联赛球队分组Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-20
 */
@Service
public class BaseTeamGroupingServiceImpl extends ServiceImpl<BaseTeamGroupingMapper, BaseTeamGrouping> implements IBaseTeamGroupingService
{
    @Autowired
    private BaseTeamGroupingMapper baseTeamGroupingMapper;
    @Autowired
    LoginUserSetUtil loginUserSetUtil;
    @Autowired
    private IBaseTeanGroupingPlayTeamService iBaseTeanGroupingPlayTeamService;
    @Autowired
    private IBaseBasketballTeamService iBaseBasketballTeamService;
    /**
     * 查询联赛球队分组
     * 
     * @param id 联赛球队分组主键
     * @return 联赛球队分组
     */
    @Override
    public BaseTeamGrouping selectBaseTeamGroupingById(Long id)
    {
        return baseTeamGroupingMapper.selectBaseTeamGroupingById(id);
    }

    /**
     * 查询联赛球队分组列表
     * 
     * @param baseTeamGrouping 联赛球队分组
     * @return 联赛球队分组
     */
    @Override
    public List<BaseTeamGrouping> selectBaseTeamGroupingList(BaseTeamGrouping baseTeamGrouping)
    {
        baseTeamGrouping.setContestId(SecurityUtils.getContestId());
        List<BaseTeamGrouping> baseTeamGroupings = baseTeamGroupingMapper.selectBaseTeamGroupingList(baseTeamGrouping);
        if (CollUtil.isEmpty(baseTeamGroupings)){
            return new ArrayList<>();
        }
        Set<Long> collect = baseTeamGroupings.stream().map(BaseTeamGrouping::getId).collect(Collectors.toSet());
        List<BaseTeanGroupingPlayTeam> baseTeanGroupingPlayTeams = iBaseTeanGroupingPlayTeamService.list(
                Wrappers.<BaseTeanGroupingPlayTeam>lambdaQuery().in(BaseTeanGroupingPlayTeam::getTeamGroupingId,collect));
        Map<Long, List<BaseTeanGroupingPlayTeam>> collect1 = baseTeanGroupingPlayTeams.stream().collect(Collectors.groupingBy(BaseTeanGroupingPlayTeam::getTeamGroupingId));
        baseTeamGroupings.forEach(vo ->{
            List<BaseTeanGroupingPlayTeam> baseTeanGroupingPlayTeams1 = collect1.get(vo.getId());
            if (CollUtil.isNotEmpty(baseTeanGroupingPlayTeams1)){
                vo.setNum(baseTeanGroupingPlayTeams1.size());
            }
        });
        return baseTeamGroupings;
    }

    /**
     * 新增联赛球队分组
     * 
     * @param baseTeamGrouping 联赛球队分组
     * @return 结果
     */
    @Override
    public int insertBaseTeamGrouping(BaseTeamGrouping baseTeamGrouping)
    {
        baseTeamGrouping.setCreateTime(DateUtils.getNowDate());
        loginUserSetUtil.populateFields(baseTeamGrouping, 1);
        return baseTeamGroupingMapper.insert(baseTeamGrouping);
    }

    /**
     * 修改联赛球队分组
     * 
     * @param baseTeamGrouping 联赛球队分组
     * @return 结果
     */
    @Override
    public int updateBaseTeamGrouping(BaseTeamGrouping baseTeamGrouping)
    {
        baseTeamGrouping.setUpdateTime(DateUtils.getNowDate());
        loginUserSetUtil.populateFields(baseTeamGrouping, 2);
        return baseTeamGroupingMapper.updateById(baseTeamGrouping);
    }

    /**
     * 批量删除联赛球队分组
     * 
     * @param ids 需要删除的联赛球队分组主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBaseTeamGroupingByIds(Long[] ids)
    {
        int i = baseTeamGroupingMapper.deleteBaseTeamGroupingByIds(ids);
        iBaseTeanGroupingPlayTeamService.remove(Wrappers.<BaseTeanGroupingPlayTeam>lambdaQuery().in(BaseTeanGroupingPlayTeam::getTeamGroupingId,ids));
        return i;
    }

    /**
     * 删除联赛球队分组信息
     * 
     * @param id 联赛球队分组主键
     * @return 结果
     */
    @Override
    public int deleteBaseTeamGroupingById(Long id)
    {
        return baseTeamGroupingMapper.deleteBaseTeamGroupingById(id);
    }

    @Override
    public List<BaseTeamGrouping> teamRankingList(Long contestId) {
        BaseTeamGrouping baseTeamGrouping = BaseTeamGrouping.builder().contestId(contestId).build();
        List<BaseTeamGrouping> baseTeamGroupings = baseTeamGroupingMapper.selectBaseTeamGroupingList(baseTeamGrouping);
        if (CollUtil.isEmpty(baseTeamGroupings)){
            return new ArrayList<>();
        }
        Set<Long> teamGroupingIds = baseTeamGroupings.stream().map(BaseTeamGrouping::getId).collect(Collectors.toSet());
        List<BaseTeanGroupingPlayTeam> list = iBaseTeanGroupingPlayTeamService.list(Wrappers.<BaseTeanGroupingPlayTeam>lambdaQuery()
                .in(BaseTeanGroupingPlayTeam::getTeamGroupingId, teamGroupingIds));
        if (CollUtil.isEmpty(list)){
            return baseTeamGroupings;
        }
        Set<Long> teamIds = list.stream().map(BaseTeanGroupingPlayTeam::getBasketballTeamId).collect(Collectors.toSet());
        List<BaseBasketballTeam> baseBasketballTeams = iBaseBasketballTeamService.listByIds(teamIds);
        Map<Long, BaseBasketballTeam> teamIdMap = baseBasketballTeams.stream().collect(Collectors.toMap(BaseBasketballTeam::getId, Function.identity(), (k, v) -> k));
        Map<Long, List<BaseTeanGroupingPlayTeam>> teamGroupingIdMap = list.stream().collect(Collectors.groupingBy(BaseTeanGroupingPlayTeam::getTeamGroupingId));
        baseTeamGroupings.forEach(vo ->{
            List<BaseTeanGroupingPlayTeam> baseTeanGroupingPlayTeams = teamGroupingIdMap.get(vo.getId());
            if (CollUtil.isNotEmpty(baseTeanGroupingPlayTeams)){

                baseTeanGroupingPlayTeams.forEach(team ->{
                    team.setBaseBasketballTeam(teamIdMap.get(team.getBasketballTeamId()));
                });
                baseTeanGroupingPlayTeams.forEach( team ->{
                    long l = team.getWinNum() + team.getLossNum();
                    if (team.getWinNum() == 0 || l == 0){
                        team.setChanceWin(BigDecimal.valueOf(0));
                    }else{
                        BigDecimal divide = BigDecimal.valueOf(team.getWinNum()).divide(BigDecimal.valueOf(l), 2, RoundingMode.HALF_UP);
                        team.setChanceWin(divide.multiply(BigDecimal.valueOf(100)));
                    }
                    l = l - team.getAbstentionNum();
                    if(l != 0 && !team.getGoalDifference().equals(BigDecimal.ZERO)){
                        BigDecimal divide = team.getGoalDifference().divide(BigDecimal.valueOf(l), 0, RoundingMode.HALF_UP);
                        team.setGoalDifference(divide);
                    }
                });
                baseTeanGroupingPlayTeams = baseTeanGroupingPlayTeams.stream()
                        .sorted(Comparator.comparing(BaseTeanGroupingPlayTeam::getPoints)
                                .thenComparing(BaseTeanGroupingPlayTeam::getWinNum)
                                .thenComparing(BaseTeanGroupingPlayTeam::getGoalDifference)
                                .reversed())
                        .collect(Collectors.toList());
            }
            vo.setTeanGroupingPlayTeamList(baseTeanGroupingPlayTeams);
        });
        return baseTeamGroupings;
    }
}
